package cn.kgc.springmvc.day02.controller;

import cn.kgc.springmvc.day02.entity.ResponseResult;
import cn.kgc.springmvc.day02.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/5/6
 * @description  springmvc响应数据格式
 */
@Controller
@RequestMapping("res")
public class ResponseController {

    //  响应的数据是ModelAndView 类型   ->  视图解析器  -> 转发视图
    @RequestMapping("m1")
    public ModelAndView method1() {

        System.out.println("hello  springmvc");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("info","参数的接收");

        return modelAndView;
    }


    //  String  默认是视图名    ->  视图解析器  -> 转发视图
    @RequestMapping("m2")
    public String method2() {
        return "hello";
    }


    //  String  默认是视图名    ->  视图解析器  -> 转发视图
    @RequestMapping("m3")
    public String method3(Model model) {
        model.addAttribute("info","hello model");
        return "hello";
    }


    @RequestMapping("m4")
    public void method4(HttpServletRequest  request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/hello.jsp").forward(request,response);
    }


    //  ResponseResult  ->  jackson ->  json     json格式的数据不会在经过视图解析器
    @RequestMapping("m5")
    @ResponseBody
    public ResponseResult method5()  {

        User user = new User();
        user.setUsername("tom");
        user.setPassword("123456");
        user.setSex(1);
        user.setSex(20);

        List<User> list = Arrays.asList(user, user, user);

        return new ResponseResult().setCode(0)
                .setMessage("查询成功")
                .setData(list);
    }

    @RequestMapping("m6")
    @ResponseBody
    public List<User> method6()  {

        User user = new User();
        user.setUsername("tom");
        user.setPassword("123456");
        user.setSex(1);
        user.setSex(20);

        List<User> list = Arrays.asList(user, user, user);

        return list;
    }


}
